package controller;

import bean.Account;
import bean.Detail;
import dao.AccountDao;
import dao.DetailDao;
import dao.impl.AccountDaoImpl;
import dao.impl.DetailDaoImpl;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import util.AlertUtil;
import util.FxmlUtil;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Optional;

public class OperateController {
    public TextField money;
    private AccountDao accountDao = new AccountDaoImpl();
    private DetailDao detailDao = new DetailDaoImpl();
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public void cancelAction() {
        Stage stage = (Stage) this.money.getScene().getWindow();
        Scene scene = FxmlUtil.SCENE.get("main");
        stage.setScene(scene);
        stage.setTitle("ATM - 首页");
    }

    public void okAction() {
        float moneyText = Float.parseFloat(money.getText());
        Account account = (Account) FxmlUtil.DATA.get("account");
        int type = (int) FxmlUtil.DATA.get("type");

        String success = type == 1 ? "存款成功" : "取款成功";
        String fail = type == 1 ? "存款失败" : "取款失败";
        String operate = type == 1 ? "存款" : "取款";
        Detail detail = new Detail(account.getAccNo(), operate, moneyText, sdf.format(new Date(System.currentTimeMillis())));
        moneyText = type == 1 ? moneyText : -moneyText;

        int num = accountDao.update(account.getAccNo(), moneyText);
        if (num > 0) {
            detailDao.insert(detail);

            Optional<ButtonType> alert = AlertUtil.alert(Alert.AlertType.INFORMATION, success,
                    success + ",是否继续操作？", ButtonType.YES, ButtonType.NO);
            if (alert.isPresent() && alert.get() == ButtonType.NO) {
                cancelAction();
            }
        } else {
            Optional<ButtonType> alert = AlertUtil.alert(Alert.AlertType.INFORMATION, fail,
                    fail + ",是否继续操作？", ButtonType.YES, ButtonType.NO);
            if (alert.isPresent() && alert.get() == ButtonType.NO) {
                cancelAction();
            }
        }

        money.setText("");
    }

    public void resetAction() {
        money.setText("");
    }
}
